/*
* Copyright (C) 2024-2025 Deepin Co., Ltd.
*
* Author:      zhangbingyi <zhangbingyi@uniontech.com>
*
* Maintainer:  zhangbingyi <zhangbingyi@uniontech.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
#include "trustedprotectionwidget.h"
#include "trustedprotectiondefinition.h"
#include "tptabledelegate.h"
#include "tptablemodel.h"
#include "invokers/invokerfactory.h"
#include "common.h"
#include "comdata.h"
#include "compixmap.h"
#include "dialogmanage.h"
#include "widgets/ddialog.h"
#include "widgets/hfloatingdialog.h"
#include "widgets/hfloatingmessage.h"

#include <QIcon>
#include <QFileDialog>
#include <QApplication>
#include <QGridLayout>
//#include <QMimeDatabase>

#define SET_ACC_NAME(contral, name) SET_ACCESS_NAME(contral, TrustedProtectionWidget, name)


#define IMA_STATES_DISABLED 2
#define IMA_STATES_ENABLED 3

TrustedProtectionWidget::TrustedProtectionWidget(QWidget *parent)
    : QFrame(parent)
    , m_mainFrame(nullptr)
    , m_title(nullptr)
    , m_switchItem(nullptr)
    , m_describtion(nullptr)
    , m_tableView(nullptr)
    , m_dfTableView(nullptr)
    , m_globalCheckBox(nullptr)
    , m_counterLable(nullptr)
    , m_addContentButton(nullptr)
    , m_removeContentButton(nullptr)
    , m_dataModel(nullptr)
//    , m_bgGroup(nullptr)
    , m_isEnabled(false)
    , m_IMAInvoker(nullptr)
    , m_MonitorInvoker(nullptr)
    , m_isModelInited(false)
    , m_tableDelegate(nullptr)
{
    SET_ACC_NAME(this, tpMainWindow);
    m_IMAInvoker = InvokerFactory::GetInstance().CreateInvoker("com.deepin.daemon.ImaDaemon",
                                                               "/com/deepin/daemon/ImaDaemon",
                                                               "com.deepin.daemon.ImaDaemon",
                                                               ConnectType::SYSTEM, this);

    m_MonitorInvoker = InvokerFactory::GetInstance().CreateInvoker("com.deepin.defender.MonitorNetFlow",
                                                                   "/com/deepin/defender/MonitorNetFlow",
                                                                   "com.deepin.defender.MonitorNetFlow",
                                                                   ConnectType::SYSTEM, this);

    initUI();
    initSwitch();
    initConnection();
    setFont();
    m_dataModel->initData();
}

// 通知校验文件类型
// 如果类型正确，通知model更新数据库，如果数据库插入成功，更新model,返回结果
bool TrustedProtectionWidget::verifyContentFileType(QString path)
{
    // 判断一下是否符号链接，是的话则不处理
    QFileInfo file(path);
    if (file.exists()) {
        // 根据系统安全组结论
        // 符号文件排除
        if (file.isSymLink()) {
            return false;
        }

        QString fileMimeTypeLinux;
        QProcess fileCheck;
        QString cmdLine = QString("file --mime-type \"%1\"").arg(path);
        fileCheck.start(cmdLine);
        fileCheck.waitForFinished(1000);
        QString rst = fileCheck.readAll();
        fileCheck.close();

        // 检查返回结果是否包含文件名，否则为错误结果
        if (!rst.contains(file.fileName())) {
            return false;
        }

        QStringList rstList = rst.split(":");
        if (rstList.size() != 2) {
            return false;
        }

        fileMimeTypeLinux = rstList.at(1);
        // 移除空格 换行
        fileMimeTypeLinux.remove(' ');
        fileMimeTypeLinux.remove('\n');
        fileMimeTypeLinux.remove('\r');

        // 注意 QT 的QMimeDatabase与系统自带不同步
//        QMimeDatabase db;
//        QString fileMimeTypeQt = db.mimeTypeForFile(file).name();

//        if (kFileNameList.contains(fileMimeTypeLinux) || kFileNameList.contains(fileMimeTypeQt)) {
//            return true;
//        }
        return true;
    }

    return false;
}

void TrustedProtectionWidget::setWidgetDisabled(bool isDisable)
{
    m_globalCheckBox->setDisabled(isDisable);
    m_addContentButton->setDisabled(isDisable);
    m_removeContentButton->setDisabled(isDisable);
    // m_tableView->setDisabled(isDisable);
    m_tableDelegate->syncDisableStatus(isDisable);
    // m_dfTableView->setDisabled(isDisable);
    updateCounterCheckBoxStatus();
    createEditor();
    m_tableView->update();
}

void TrustedProtectionWidget::onSyncStatusEnabled(bool rst)
{
    bool status = false;
    if (rst) {
        QDBusMessage msg = DBUS_BLOCK_INVOKE(m_IMAInvoker, "GetTemporaryState");
        GET_MESSAGE_VALUE(int, currentFlag, msg);
        switch (currentFlag) {
        case IMAStatusEnabled:
            status = true;
            break;
        case IMAStatusDisabled:
            status = false;
            break;
        default:
            status = false;
            break;
        }
    }
    m_isEnabled = status;
    m_switchItem->setEnabled(true);
    m_switchItem->setSwitchStatus(status);
    setWidgetDisabled(!status);
}

void TrustedProtectionWidget::resizeEvent(QResizeEvent *event)
{
    QFrame::resizeEvent(event);

    //设置m_bgGroup 的大小
//    if (m_bgGroup)
//        m_bgGroup->setFixedSize(size());
}

void TrustedProtectionWidget::paintEvent(QPaintEvent *event)
{
    // 在这里控制功能说明标签与“移除保护”按钮的缩略
    QFontMetrics buttonFM(m_removeContentButton->font());
    QString buttonStr = buttonFM.elidedText(tr("Unprotect", "button"), Qt::TextElideMode::ElideMiddle, m_removeContentButton->width() - 10);
    m_removeContentButton->setText(buttonStr);

    QFontMetrics describtionFM(m_describtion->font());
    QString desStr = describtionFM.elidedText(tr("Protect the integrity of system core components. If enabled, once the integrity is damaged, the corresponding protection policy will be executed."), Qt::TextElideMode::ElideMiddle, m_describtion->width() - 10);
    m_describtion->setText(desStr);

    return QFrame::paintEvent(event);
}

// 给各个控件设置字体
void TrustedProtectionWidget::setFont()
{
    // title T5 bold
    QFont ft = m_title->font();
    ft.setBold(true);
    m_title->setFont(ft);
//    DFontSizeManager::instance()->bind(m_title, DFontSizeManager::T5);

    //DFontSizeManager::instance()->bind(m_describtion, DFontSizeManager::T8);
//    DFontSizeManager::instance()->bind(m_counterLable, DFontSizeManager::T8);

//    DFontSizeManager::instance()->bind(m_addContentButton, DFontSizeManager::T8);
//    DFontSizeManager::instance()->bind(m_removeContentButton, DFontSizeManager::T8);
//    DLabel *switchLable = m_switchItem->findChild<DLabel *>();
//    DFontSizeManager::instance()->bind(switchLable, DFontSizeManager::T6);
}

void TrustedProtectionWidget::initUI()
{
    //将　widget　加入到一个新建的　DBackgroundGroup中
    QVBoxLayout *bglayout = new QVBoxLayout(this);
    bglayout->setContentsMargins(0, 5, 0, 0);
    bglayout->setSpacing(0);
//    m_bgGroup = new DBackgroundGroup(bglayout, this);
//    m_bgGroup->setBackgroundRole(QPalette::Window);
    QWidget *mainWindow = new QWidget(this);
    bglayout->addWidget(mainWindow);
    //将 m_bgGroup 沉底
//    m_bgGroup->lower();
    //设置m_bgGroup 的大小
//    m_bgGroup->setFixedSize(size());

    m_title = new QLabel(this);
    SET_ACC_NAME(m_title, tpMainTitle);
    m_title->setText(tr("Trusted Protection"));
    m_title->setContentsMargins(10, 0, 0, 0);
    m_title->setFixedHeight(37);

    m_switchItem = new ProtectionSwitchItem(this);
    m_switchItem->resetUI();
    m_switchItem->setText(tr("Execution prevention"));
    SET_ACC_NAME(m_switchItem, switchCheckItem);
    // 这里需要根据gsetting设置开关状态

    m_describtion = new QLabel(this);
    SET_ACC_NAME(m_describtion, tpDescribtion);
//    DFontSizeManager::instance()->bind(m_describtion, DFontSizeManager::T8);
    QPalette descrPal;
    descrPal.setColor(QPalette::WindowText, QColor("#526A7F"));
    m_describtion->setPalette(descrPal);
    QFont descrFont = m_describtion->font();
//    descrFont.setWeight(QFont::Medium);
    m_describtion->setFont(descrFont);
    SET_ACC_NAME(m_describtion, tpDescribtion);
    m_describtion->setAlignment(Qt::AlignTop);
    // 文本设置在paintEvent中
    m_describtion->setContentsMargins(10, 0, 15, 0);
    m_describtion->setWordWrap(false);
    // 因为超长省略而添加toolTip
    m_describtion->setToolTip(tr("Protect the integrity of system core components. If enabled, once the integrity is damaged, the corresponding protection policy will be executed."));
    m_describtion->setFixedHeight(34);

    initTable();

    m_globalCheckBox = new QCheckBox(this);
    SET_ACC_NAME(m_globalCheckBox, globalCheckBox)
    m_globalCheckBox->setChecked(false);

    // 统计值
    m_counterLable = new QLabel(this);
    SET_ACC_NAME(m_counterLable, counterLable);
    // 初始时，0选中
    m_counterLable->setText(tr("%1 rules (%2 selected)").arg(m_dataModel->rowCount()).arg(0));
    QPalette counterPal;
    counterPal.setColor(QPalette::WindowText, QColor("#526A7F"));
    m_counterLable->setPalette(counterPal);
    SET_ACC_NAME(m_counterLable, counterLable);
    // 按钮
    m_addContentButton = new QPushButton(this);
    SET_ACC_NAME(m_addContentButton, addButton);
    m_addContentButton->setText(tr("Add", "button"));
    m_addContentButton->setFixedSize(160, 36);

    m_removeContentButton = new QPushButton(this);
    SET_ACC_NAME(m_removeContentButton, removeButton);
    // 为解决维语文字遮挡问题，文本设置在paintEvent中
    m_removeContentButton->setFixedSize(160, 36);

    // QHBoxLayout *bottomLayout = new QHBoxLayout;
    QGridLayout *bottomLayout = new QGridLayout;
    bottomLayout->setContentsMargins(10, 18, 10, 0);
    bottomLayout->setSpacing(9);
    bottomLayout->setColumnMinimumWidth(0, 20);
    //bottomLayout->setRowMinimumHeight(0, 36);
    bottomLayout->addWidget(m_globalCheckBox, 0, 0, Qt::AlignLeft);
    //bottomLayout->addSpacing(10);
    bottomLayout->setColumnMinimumWidth(1, 356);
    bottomLayout->addWidget(m_counterLable, 0, 1, Qt::AlignLeft);
    bottomLayout->setColumnMinimumWidth(2, 160);
    bottomLayout->addWidget(m_removeContentButton, 0, 2, Qt::AlignRight);
    bottomLayout->setColumnMinimumWidth(3, 160);
    bottomLayout->addWidget(m_addContentButton, 0, 3, Qt::AlignRight);
    //bottomLayout->setAlignment(Alignment);

    QWidget *bottomWidget = new QWidget;
    bottomWidget->setFixedHeight(56);
    bottomWidget->setLayout(bottomLayout);

    QVBoxLayout *contentLayout = new QVBoxLayout;
    contentLayout->setContentsMargins(0, 0, 0, 0);
    contentLayout->setSpacing(0);
    contentLayout->addWidget(m_title, 0, Qt::AlignTop);
    //contentLayout->addSpacing(10);
    contentLayout->addWidget(m_switchItem);
    contentLayout->addSpacing(5);
    contentLayout->addWidget(m_describtion);
    contentLayout->addStretch();
    //contentLayout->addSpacing(1);
    contentLayout->addWidget(m_dfTableView);
    //contentLayout->addSpacing(5);
    //contentLayout->addLayout(bottomLayout, Qt::AlignBottom);
    contentLayout->addWidget(bottomWidget, Qt::AlignBottom);

    mainWindow->setLayout(contentLayout);
}

void TrustedProtectionWidget::initConnection()
{
    // remove enable/disable event
    // counting event
    connect(m_dataModel, SIGNAL(itemChanged(QStandardItem*)), this, SLOT(updateCounter(QStandardItem*)));
    connect(m_dataModel, SIGNAL(rowsRemoved(const QModelIndex &, int, int)), this, SLOT(dataModelRowsRemoved(const QModelIndex &, int , int )));

    // policy changed event
    connect(m_dataModel, SIGNAL(itemChanged(QStandardItem *)), this, SLOT(policyChanged(QStandardItem *)));
    // select/unselect all event
    connect(m_globalCheckBox, SIGNAL(clicked(bool)), this, SLOT(selectAll(bool)));
    // add event
    connect(m_addContentButton, SIGNAL(pressed()), this, SLOT(addObject()));
    // remove event
    connect(m_removeContentButton, SIGNAL(pressed()), this, SLOT(removeObjects()));

    // switch on/off event
    connect(m_switchItem, SIGNAL(switchChanged(bool)), this, SLOT(syncStatus(bool)));
    connect(m_dataModel, SIGNAL(NoticeModelInitFinished()), this, SLOT(NoticeModelInitFinished()));

    // 有对象插入时创建下拉框
    connect(m_dataModel, SIGNAL(rowsInserted(const QModelIndex &, int , int)), this, SLOT(createEditors(const QModelIndex &, int , int)));
    connect(m_dataModel, SIGNAL(NoticeRowInserted()), this, SLOT(rowAdded()));
    // 从IMA同步状态
    if (m_IMAInvoker) {
        m_IMAInvoker->Connect("StateNotification", this, SLOT(onSyncStatusEnabled(bool)));
    }
}

void TrustedProtectionWidget::initSwitch()
{
    setWidgetDisabled(true);

    m_switchItem->setSwitchStatus(false);

    // 初始化开关状态
    if (m_IMAInvoker) {
        QDBusMessage msg = DBUS_BLOCK_INVOKE(m_IMAInvoker, "GetState");
        if (msg.errorMessage().isEmpty()) {
            // 处理开关
            GET_MESSAGE_VALUE(int, imaState, msg);

            m_isEnabled = imaState == IMA_STATES_ENABLED;
            m_switchItem->syncIMAStatus(m_isEnabled);
            switch (imaState) {
            case 2:
                m_switchItem->enableSwitch(true);
                break;
            case 3:
                m_switchItem->enableSwitch(true);
                m_switchItem->setSwitchStatus(true);
                setWidgetDisabled(false);

                break;
            default:
                break;
            }
        }
    }
}

void TrustedProtectionWidget::initTable()
{
    m_dataModel = new TPTableModel(this);
    m_tableView = new QTableView(this);

    m_tableDelegate = new TPTableDelegate(this);
    m_tableView->setItemDelegate(m_tableDelegate);
    m_tableDelegate->syncDisableStatus(!m_tableView->isEnabled());
    SET_ACC_NAME(m_tableView, tableView);

    m_dfTableView = new DefenderTable(this);
    SET_ACC_NAME(m_dfTableView, dfTableView);
    m_dfTableView->setTableAndModel(m_tableView, m_dataModel);
    m_dfTableView->setFixedHeight(400);

    // 不需要排序
    m_tableView->setSortingEnabled(false);
    // 表头高36
    m_tableView->horizontalHeader()->setMaximumHeight(35);
    m_tableView->horizontalHeader()->setMinimumHeight(35);
    // 行高
    QHeaderView *verticalHeader = m_tableView->verticalHeader();
//    verticalHeader->setSectionResizeMode(QHeaderView::Fixed);
    verticalHeader->setDefaultSectionSize(48);

    // 默认宽度
    m_tableView->setColumnWidth(OBJECT_COLUMN, 175);
    m_tableView->setColumnWidth(PATH_COLUMN, 251);
    m_tableView->setColumnWidth(STATUS_COLUMN, 120);
    m_tableView->setColumnWidth(POLICY_COLUMN, 174);

    // https://pms.uniontech.com/zentao/task-view-85837.html ui要求移除
    // m_tableView->setToolTip(tr("Protect the integrity of core components"));

    m_tableView->setIconSize(QSize(16, 16));
    m_tableView->setMouseTracking(true);
}

void TrustedProtectionWidget::initModel()
{
    m_dataModel = new TPTableModel(this);
    // model 的初始化操作
    m_dataModel->initData();
}

void TrustedProtectionWidget::updateCounterAfterInsert()
{
    if (!m_checkedItems.count()) {
        m_globalCheckBox->setChecked(false);
    }

    if (m_checkedItems.count() == getCustomItemCount() && m_checkedItems.count() != 0) {
        m_globalCheckBox->setChecked(true);
    } else {
        m_globalCheckBox->setChecked(false);
    }

    m_counterLable->setText(tr("%1 rules (%2 selected)").arg(m_dataModel->rowCount()).arg(m_checkedItems.count()));

    if (m_isEnabled) {
        m_removeContentButton->setDisabled(!m_checkedItems.count());
    }
}

void TrustedProtectionWidget::updateCounter(QStandardItem *item)
{
    // check the flag of select
    // refresh counter
    // if none is selected, disable remove button, uncheck global checkbox
    if (item->index().column() != OBJECT_COLUMN) {
        return;
    }

    if (item->data(CHECKED_STATUS_ROLE).toBool()) {
        m_checkedItems.append(item);
    } else {
        m_checkedItems.removeAll(item);
    }

    updateCounterCheckBoxStatus();
    updateCounterAfterInsert();
}

void TrustedProtectionWidget::policyChanged(QStandardItem *item)
{
    // check is policy changed
    // pop up restart diologs
    // do nothing now
    if (item->index().column() != POLICY_COLUMN) {
        return;
    }
}

// 界面上全选 反选逻辑
void TrustedProtectionWidget::selectAll(bool state)
{
    int row = m_dataModel->rowCount();
    while (row) {
        // 更新索引并设置数据
        row--;
        QModelIndex index = m_dataModel->index(row, OBJECT_COLUMN);
        if (index.data(POLICY_TYPE_ROLE).toInt() == POLICY_CUSTOM) {
            m_dataModel->setData(index, state, CHECKED_STATUS_ROLE);
        }
    }
}

void TrustedProtectionWidget::addObject()
{
    // response to add
    // need a file selector here
    // verity the file type

    // pop up restart dialogs
    QString fileName = QFileDialog::getOpenFileName(this, tr("Open file"), QDir::homePath(), tr("All Files(*)"));
    // 按钮归位
    // DSuggestButton响应pressed信号时，为什么按下后不自动归位
    m_addContentButton->setDown(false);

    // 选择时退出了
    if (fileName.isEmpty()) {
        return;
    }

    // 结果不正确时弹框
    if (!verifyContentFileType(fileName)) {
        QMessageBox *message = new QMessageBox(this);
        message->setIcon(QMessageBox::Warning);
        message->setText(tr("Select a right file please"));
        message->setWindowTitle(tr("Warning"));

        // 确定推荐
        QPushButton *okBtn = new QPushButton(message);
        okBtn->setText(tr("OK", "button"));
        okBtn->setObjectName("okButton");
        okBtn->setAccessibleName("fdialog_okButton");
        okBtn->setAttribute(Qt::WA_NoMousePropagation);
        message->addButton(okBtn, QMessageBox::AcceptRole);
        connect(message, SIGNAL(buttonClicked(QAbstractButton *)), this, SLOT(addObjectHelp(QAbstractButton*)));
        message->exec();
    } else {
        m_dataModel->insertPolicy(fileName);
        QString logInfo = tr("Added the protected component: %1");
        DBUS_NOBLOCK_INVOKE(m_MonitorInvoker, "AddSecurityLog", SECURITY_LOG_TYPE_TOOL, logInfo.arg(fileName));
    }
}

void TrustedProtectionWidget::removeObjects()
{
    // response to remove
    // noticy and wait for sql remove finish
    // then remove data in model

    int removeCount = m_checkedItems.count();
    if (removeCount) {
        foreach (auto it, m_checkedItems) {
            if (m_dataModel->removeRows(it->index().row(), 1)) {
                m_checkedItems.removeAll(it);
            }
        }
        // 确实地发生了删除行为
        if (removeCount != m_checkedItems.count()) {
            HFloatingDialog *message = new HFloatingDialog(parentWidget());
            message->setText(tr("Removed the protection, please reboot for the changes to take effect"));
            message->exec();
        }
    }
    updateCounterCheckBoxStatus();
    updateCounterAfterInsert();
}

void TrustedProtectionWidget::enableProtection(bool isEnabled)
{
    if (isEnabled) {
        initConnection();

    } else {
        // 置灰按钮与勾选框
        this->disconnect();
    }

    // pop up restart diologs
}

void TrustedProtectionWidget::createEditor()
{
    int size = 0;
    int itemsCount = m_dataModel->rowCount();
    while (size < itemsCount) {
        QModelIndex tmp = m_dataModel->index(size, POLICY_COLUMN);
//        if (m_tableView->isPersistentEditorOpen(tmp)) {
            m_tableView->closePersistentEditor(tmp);
//        }
        m_tableView->openPersistentEditor(tmp);
        size++;
    }
}

void TrustedProtectionWidget::createEditors(const QModelIndex &parent, int first, int last)
{
    Q_UNUSED(parent);
    while (last >= first) {
        QModelIndex tmp = m_dataModel->index(first, POLICY_COLUMN);
//        if (m_tableView->isPersistentEditorOpen(tmp)) {
            m_tableView->closePersistentEditor(tmp);
//        }
        m_tableView->openPersistentEditor(tmp);
        first++;
    }
}

void TrustedProtectionWidget::syncStatus(bool status)
{
    if (m_isEnabled == status) {
        return;
    }
    m_isEnabled = status;
    QString text;
    text = m_isEnabled ? tr("Integrity protection enabled, please reboot for the changes to take effect. Note: If core components are tampered with, system errors may occur.")
                       : tr("Integrity protection disabled, please reboot for the changes to take effect");

    int targetStage = !m_isEnabled ? IMA_STATES_DISABLED : IMA_STATES_ENABLED;
    QDBusMessage msg = DBUS_NOBLOCK_INVOKE(m_IMAInvoker, "SetState", targetStage);

    if (msg.errorMessage().isEmpty()) {
        HFloatingMessage *message = new HFloatingMessage(parentWidget());
        message->setText(text);
        message->setDuration(5000);
        message->exec();

        setWidgetDisabled(!m_isEnabled);

        QString loginfo = m_isEnabled ? tr("Execution prevention: ON") : tr("Execution prevention: OFF");
        DBUS_BLOCK_INVOKE(m_MonitorInvoker, "AddSecurityLog", SECURITY_LOG_TYPE_TOOL, loginfo);
        m_switchItem->setEnabled(false);
    } else {
        m_isEnabled = !m_isEnabled;
        m_switchItem->setSwitchStatus(m_isEnabled);
    }

    selectAll(0);
    updateCounterCheckBoxStatus();
    updateCounterAfterInsert();
}

void TrustedProtectionWidget::updateCounterCheckBoxStatus()
{
    // 检索所有自定义用户策略对象
    int itemsCount = m_dataModel->rowCount();
    for (int i = 0; i < itemsCount; i++) {
        QModelIndex index = m_dataModel->index(i, POLICY_COLUMN);
        if (m_dataModel->data(index, POLICY_TYPE_ROLE).toInt() == POLICY_CUSTOM) {
            // 存在自定义策略对象
            // 如果是enable状态，则将其置为enable
            if (m_isEnabled) {
                m_globalCheckBox->setDisabled(false);
                m_removeContentButton->setDisabled(false);
                return;
            }
        }
    }

    m_globalCheckBox->setChecked(false);
    m_globalCheckBox->setDisabled(true);
    m_removeContentButton->setDisabled(true);
}

void TrustedProtectionWidget::addObjectHelp(QAbstractButton *)
{
    QMessageBox *dialog = qobject_cast<QMessageBox*>(sender());
    dialog->accept();
}

void TrustedProtectionWidget::rowAdded()
{
    // 添加行时必然置空全选checkbox
    if (m_isEnabled && m_globalCheckBox->isEnabled()) {
        m_globalCheckBox->setCheckState(Qt::CheckState::Unchecked);
    }

    updateCounterCheckBoxStatus();
    updateCounterAfterInsert();

    if (m_isModelInited) {
        HFloatingDialog *message = new HFloatingDialog(parentWidget());
        message->setText(tr("Added successfully, please reboot for the changes to take effect"));
        message->exec();
    }
}

int TrustedProtectionWidget::getCustomItemCount()
{
    int rows = m_dataModel->rowCount();
    int count = 0;
    for (int i = 0; i < rows; i++) {
        QModelIndex index = m_dataModel->index(i, POLICY_COLUMN);
        int policyType = index.data(POLICY_TYPE_ROLE).toInt();
        if (POLICY_CUSTOM == policyType) {
            count++;
        }
    }
    return count;
}

void TrustedProtectionWidget::dataModelRowsRemoved(const QModelIndex &parent, int first, int last)
{
    Q_UNUSED(parent);
    Q_UNUSED(last);
    Q_UNUSED(first);

    m_checkedItems.clear();
    int rows = m_dataModel->rowCount();
    for (int index = 0; index < rows; index++) {
        QStandardItem *indexItem = m_dataModel->item(index);
        if (indexItem->data(POLICY_TYPE_ROLE).toInt() == POLICY_CUSTOM && indexItem->data(CHECKED_STATUS_ROLE).toBool()) {
            m_checkedItems.push_back(indexItem);
        }
    }
    this->updateCounterCheckBoxStatus();
    this->updateCounterAfterInsert();
}

void TrustedProtectionWidget::NoticeModelInitFinished()
{
    m_isModelInited = true;
}

void ProtectionSwitchItem::resetUI()
{
    QWidget *mainWidget = findChild<QWidget *>();
    QBoxLayout *layout = qobject_cast<QBoxLayout *>(mainWidget->layout());
    // 重设上下边界13
    layout->setContentsMargins(8, 0, 8, 0);
    // 重设行高
    setFixedHeight(48);

    m_tipLabelWithColor = new QLabel(this);
    QString tipsInfo = QString("(%1)").arg(tr("System core components are under the protection"));
    m_tipLabelWithColor->setText(tipsInfo);
//    m_tipLabelWithColor->setElideMode(Qt::ElideLeft);
//    DFontSizeManager::instance()->bind(m_tipLabelWithColor, DFontSizeManager::T8);
    // 将控件插入指定位置
    layout->insertWidget(1, m_tipLabelWithColor);

    QPalette pa = m_tipLabelWithColor->palette();
    pa.setColor(QPalette::Text, QColor("#FF5D00"));
    m_tipLabelWithColor->setPalette(pa);

    m_tipLabelWithColor->setVisible(false);

    setBackgroundType(HFrame1::Normal);
}

void ProtectionSwitchItem::syncIMAStatus(bool isIMAEnabled)
{
    m_tipLabelWithColor->setVisible(isIMAEnabled);
}
